<template>
  <q-select
    v-model="model"
    :options="options"
    @clear="onClear"
    @filter="filterFn"
    clearable
    borderless
    filled
    use-input
    dense
    :dark="dark"
    color="grey-5"
    :style="{ width: width + 'px', height: '40px' }"
    autocomplete="off"
  />
</template>

<script lang="ts">
import uniq from 'lodash/uniq';
import { useQuasar } from 'quasar';
import { emitter } from 'src/emitter';
import { defineComponent, PropType, ref, watch } from 'vue';
export default defineComponent({
  name: 'search-select',

  props: {
    field: {
      type: String,
      required: true,
    },
    id: {
      type: String,
    },
    width: {
      type: Number,
      default: 200,
    },
    nullWord: {
      type: String,
      default: '',
    },
    /**
     * 映射关系, 如 {[电文描述]: 电文 ID}
     */
    map: {
      type: Object as PropType<Record<string | number, string>>,
    },
    rows: {
      type: Array as PropType<any[]>,
    },
    dark: {
      type: Boolean,
      default: true,
    },
  },

  setup(props) {
    const $q = useQuasar();
    const model = ref('');
    const rawOptions = ref<any[]>();
    watch(
      () => props.rows,
      () => {
        rawOptions.value = uniq(props.rows?.map(row => row[props.field]));
      },
    );

    const options = ref<any[]>([]);
    const filterFn = (val: string, update: any) => {
      update(() => {
        const needle = val.toLowerCase();
        if (!rawOptions.value) {
          return $q.notify({ message: '请在数据加载完成后使用', color: 'negative' });
        }
        options.value = rawOptions.value.filter(v => String(v).toLowerCase().indexOf(needle) > -1);
      });
    };

    watch(model, () => {
      if (!model.value) {
        return;
      }

      let modelValue = model.value;
      // 如果是带映射关系的如 {[电文描述]: 电文ID}, 则从描述获取电文 ID
      if (props.map && props.map[model.value]) {
        modelValue = props.map[model.value];
      }

      // 如果是 null 的对应词, 如 未知, 则把这个词替换为空字符串
      if (props.nullWord && modelValue === props.nullWord) {
        modelValue = '';
      }

      emitter.emit('table_search', { id: props.id, field: props.field, clause: modelValue });
    });

    const onClear = () => {
      model.value = '';
      emitter.emit('table_search', { id: props.id, field: props.field });
    };

    return { model, filterFn, options, onClear };
  },
});
</script>
